package com.quincysx.ipcdemo.demo1;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.quincysx.ipcdemo.bean.Book;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author QuincySx
 * @date 2018/5/4 上午11:04
 */
public class RemoteService extends Service {
    private final List<Book> mBooks = new ArrayList<>();

    @Override
    public void onCreate() {
        new Thread(mAddBookRunnable).start();
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mStub;
    }

    private IBookManager.Stub mStub = new IBookManager.Stub() {
        @Override
        public void addBook(Book book) throws RemoteException {
            Log.e("==客户端添加书籍==", book.toString());
            synchronized (mBooks) {
                mBooks.add(book);
            }
        }

        @Override
        public List<Book> getBookList() throws RemoteException {
            synchronized (mBooks) {
                return mBooks;
            }
        }
    };

    /**
     * 定时任务 模拟其他进程插入数据
     */
    private Runnable mAddBookRunnable = new Runnable() {
        long count = 0;

        @Override
        public void run() {
            while (true) {
                Book book = new Book();
                book.setId(count);
                book.setName("我是书#" + count);
                book.setPrice((new Random().nextInt(100) / 10d) + 10);
                synchronized (mBooks) {
                    mBooks.add(book);
                }
                try {
                    count++;
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}
